package com.mDigitalHealth.network;

import intf.mDigitalHealth.DigitalHealthFetchUserInfoRequest;
import intf.mDigitalHealth.DigitalHealthFetchUserInfoResponse;
import intf.mDigitalHealth.DigitalHealthUploadStepInfoRequest;
import intf.mDigitalHealth.DigitalHealthUploadStepInfoResponse;
import intf.mDigitalHealth.DigitalHealthUploadUserInfoRequest;
import intf.mDigitalHealth.DigitalHealthUploadUserInfoResponse;
import intf.mDigitalHealth.DigitalHealthUserLoginRequest;
import intf.mDigitalHealth.DigitalHealthUserLoginResponse;
import intf.mDigitalHealth.Hour_Step_Count;
import intf.mDigitalHealth.mDigitalHealthInterface;

import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.mDigitalHealth.common.HttpUtils;
import com.mDigitalHealth.common.Utils;
import com.mDigitalHealth.database.DataType;
import com.mDigitalHealth.database.DatabaseHelper;
import com.mDigitalHealth.database.Store;
import com.mDigitalHealth.model.DailyStep;
import com.mDigitalHealth.model.LineChartInfo;

public class DigitalHealthClient {

	/**
	 * user login method
	 * 
	 * @param name
	 * @param password
	 * @return
	 */
	// private static String _strBaseURL = "http://119.62.128.125:88/mdhs/"; //

	// "http://118.192.25.71:8080/mobilelife/servlet/";
	private static String _strBaseURL = "http://118.192.25.71:8080/mobilelife/servlet/";

	public static DigitalHealthUserLoginResponse login(String name, String password) {
		try {
			mDigitalHealthInterface client = new mDigitalHealthInterface();
			// UserLogin
			DigitalHealthUserLoginRequest loginReq = new DigitalHealthUserLoginRequest();
			loginReq.setTransactionId(String.valueOf(Utils.getSystemTiem()));
			loginReq.setLoginName(name); // test@163.com
			loginReq.setLoginPassword(password); // 123456
			loginReq.setUserNumber("13800000000");
			DigitalHealthUserLoginResponse loginRes = client.DigitalHealthUserLogin(_strBaseURL
					+ "procUserLogin", loginReq);
			return loginRes;
			/*if (loginRes == null) {
				// fail
				System.out.println("UserLogin Failed!");
			} else {
				System.out.println("");
				System.out.println("[DigitalHealthUserLogin]");
				System.out.println("Transaction_Id: "+ loginRes.getTransactionId());
				System.out.println("Login_Name: " + loginRes.getLoginName());
				System.out.println("Login_Status: " + loginRes.getLoginStatus());
				if (loginRes.getLoginStatus() == 0) {
					// 锟斤拷录锟缴癸拷,锟斤拷锟斤拷锟斤拷锟斤拷娲︼拷锟�
				} else {
					// 锟斤拷录失锟斤拷
					System.out.println("UserLogin Failed!");
				}
			}*/

		}// try
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * upload user hour step info
	 */
	public static void uploadUserHourStepInfo(Context context, String name) {
		DatabaseHelper mDatabaseHelper = null;
		Cursor mCursor = null;
		try {
			mDigitalHealthInterface client = new mDigitalHealthInterface();
			// UploadStepInfo
			DigitalHealthUploadStepInfoRequest uploadStepReq = new DigitalHealthUploadStepInfoRequest();
			mDatabaseHelper = new DatabaseHelper(context);

			mCursor = mDatabaseHelper.query(DataType.HOUR_DATA, null,
					Store.HourDataColumns.ISUPLOAD + " = ?  AND "
							+ Store.HourDataColumns.LOGIN_USER + " = ? ",
					new String[] { "0", name }, null);
			if (mCursor == null || mCursor.getCount() == 0)
				return;
			if (!Utils.isWifiEnable(context))
				return;
			int count = mCursor.getCount();
			int stepTotalIndex = mCursor
					.getColumnIndex(Store.HourDataColumns.HOUR_STEP_COUNT_TOTAL);
			int timeIndex = mCursor.getColumnIndex(Store.HourDataColumns.HOUR_STAMP);
			Hour_Step_Count[] stepCount = new Hour_Step_Count[count];
			for (int i = 0; i < count; i++) {
				mCursor.moveToPosition(i);
				Hour_Step_Count stepTmp1 = new Hour_Step_Count();
				stepTmp1._Hour_Stamp = Utils.getHourStampTime(mCursor.getLong(timeIndex));
				stepTmp1._Hour_Step_Count_Total = mCursor.getInt(stepTotalIndex);
				stepTmp1._Hour_Step_Count_High = 0;
				stepTmp1._Hour_Step_Count_Mid = stepTmp1._Hour_Step_Count_Total;
				stepTmp1._Hour_Step_Count_Low = 0;
				stepCount[i] = stepTmp1;
			}

			uploadStepReq.setTransactionId(String.valueOf(Utils.getSystemTiem()));
			uploadStepReq.setLoginName(name); // test@163.com
			uploadStepReq.setUserNumber("13308710002");
			uploadStepReq.setHourStepCount(stepCount);

			String strUploadStepReq = uploadStepReq.encode();
			System.out.println("***upload step req=" + strUploadStepReq);

			// 锟斤拷锟�
			DigitalHealthUploadStepInfoRequest uploadStepTest = new DigitalHealthUploadStepInfoRequest();
			int nResult = uploadStepTest.decode(strUploadStepReq);

			System.out.println("");
			System.out.println("[DigitalHealthUploadStepInfo]");
			System.out.println("Transaction_Id: " + uploadStepTest.getTransactionId());
			System.out.println("Login_Name: " + uploadStepTest.getLoginName());
			System.out.println("User_Number: " + uploadStepTest.getUserNumber());

			Hour_Step_Count[] stepCountSet = uploadStepTest.getHourStepCount();
			Hour_Step_Count stepCountTest = null;
			for (int i = 0; i < stepCountSet.length; i++) {
				stepCountTest = stepCountSet[i];
				System.out.println("{");
				System.out.println("   Hour_Stamp: " + stepCountTest._Hour_Stamp);
				System.out.println("   Hour_Step_Count_Total: "
						+ stepCountTest._Hour_Step_Count_Total);
				System.out.println("   Hour_Step_Count_High: "
						+ stepCountTest._Hour_Step_Count_High);
				System.out.println("   Hour_Step_Count_Mid: " + stepCountTest._Hour_Step_Count_Mid);
				System.out.println("   Hour_Step_Count_Low: " + stepCountTest._Hour_Step_Count_Low);
				System.out.println("}");
			}// for

			// UploadStepInfo
			DigitalHealthUploadStepInfoResponse uploadStepInfoRes = client
					.DigitalHealthUploadStepInfo(_strBaseURL + "procUploadStepInfo", uploadStepReq);
			;
			if (uploadStepInfoRes == null) {
				// 锟斤拷锟斤拷洗锟绞э拷锟�锟斤拷锟铰次斤拷锟斤拷锟较达拷
				System.out.println("UploadStepInfo Failed!");
			} else {
				System.out.println("");
				System.out.println("[DigitalHealthUploadStepInfoResponse]");
				System.out.println("Transaction_Id: " + uploadStepInfoRes.getTransactionId());
				System.out.println("Login_Name: " + uploadStepInfoRes.getLoginName());
				System.out.println("User_Number: " + uploadStepInfoRes.getUserNumber());
				System.out.println("Upload_Status: " + uploadStepInfoRes.getUploadStatus());
				ContentValues values = new ContentValues();
				values.put(Store.HourDataColumns.ISUPLOAD, 1);
				if (uploadStepInfoRes.getUploadStatus() == 0) {
					// 锟斤拷锟斤拷洗锟斤拷晒锟�锟斤拷锟较达拷锟斤拷锟斤拷锟斤拷,锟斤拷锟斤拷锟窖撅拷锟较达拷锟斤拷傻谋锟绞�锟铰次诧拷锟斤拷锟较达拷
					System.out.println("***upload step info success");
					for (int i = 0; i < count; i++) {
						mCursor.moveToPosition(i);
						int id = mCursor.getInt(0);
						mDatabaseHelper.update(DataType.HOUR_DATA, id, values);
					}
				} else {
					// 锟斤拷锟斤拷洗锟绞э拷锟�锟斤拷锟铰次斤拷锟斤拷锟较达拷
					System.out.println("UploadStepInfo Failed!");
				}
			}// else
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (mCursor != null) {
				mCursor.close();
				mCursor = null;
			}
			if (mDatabaseHelper != null) {
				mDatabaseHelper.close();
				mDatabaseHelper = null;
			}
		}

	}

	/**
	 * upload user info
	 */
	public static DigitalHealthUploadUserInfoResponse uploadUserInfo(String name) {
		try {
			mDigitalHealthInterface client = new mDigitalHealthInterface();
			// UploadUserInfo 通锟斤拷锟斤拷锟斤拷锟饺★拷没锟斤拷锟较拷锟捷诧拷锟斤拷锟斤拷锟斤拷
			DigitalHealthUploadUserInfoRequest uploadUserInfoReq = new DigitalHealthUploadUserInfoRequest();
			uploadUserInfoReq.setTransactionId(String.valueOf(Utils.getSystemTiem()));
			uploadUserInfoReq.setLoginName(name); // "uploaduser@163.com"
			uploadUserInfoReq.setUserNumber("13308710004");
			uploadUserInfoReq.setUserGender(1);
			uploadUserInfoReq.setUserHeight(180);
			uploadUserInfoReq.setUserWeight(80);
			uploadUserInfoReq.setStepLength(78);
			uploadUserInfoReq.setRunStepLength(80);
			uploadUserInfoReq.setDayPlanStepCount(12000);

			DigitalHealthUploadUserInfoResponse uploadUserInfoRes = client
					.DigitalHealthUploadUserInfo(_strBaseURL + "procUploadUserInfo",
							uploadUserInfoReq);
			return uploadUserInfoRes;
			/*if(uploadUserInfoRes == null)
			{
				//锟较达拷锟矫伙拷锟斤拷锟绞э拷锟�
				System.out.println("UploadUserInfo Failed!");
			}
			else
			{
				System.out.println("");
				System.out.println("[DigitalHealthUploadUserInfo]");
				System.out.println("Transaction_Id: " + uploadUserInfoRes.getTransactionId());
				System.out.println("Login_Name: " + uploadUserInfoRes.getLoginName());
				System.out.println("User_Number: " + uploadUserInfoRes.getUserNumber());
				System.out.println("Upload_Status: " + uploadUserInfoRes.getUploadStatus());
				
				if(uploadUserInfoRes.getUploadStatus() == 0)
				{
					//锟矫伙拷锟斤拷锟斤拷洗锟斤拷晒锟�
				}
				else
				{
					//锟较达拷锟矫伙拷锟斤拷锟绞э拷锟�
					System.out.println("UploadUserInfo Failed!");
				}//else
			}*/
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * Fetch User Info
	 */
	public static DigitalHealthFetchUserInfoResponse fetchUserInfo(String name) {
		try {
			mDigitalHealthInterface client = new mDigitalHealthInterface();
			// FetchUserInfo 锟斤拷锟斤拷锟较达拷锟矫伙拷锟斤拷息锟斤拷莶锟斤拷锟斤拷锟斤拷锟�
			DigitalHealthFetchUserInfoRequest fetchUserInfoReq = new DigitalHealthFetchUserInfoRequest();
			fetchUserInfoReq.setTransactionId(String.valueOf(Utils.getSystemTiem()));
			fetchUserInfoReq.setLoginName(name); // fetch@163.com
			fetchUserInfoReq.setUserNumber("13308710003");
			DigitalHealthFetchUserInfoResponse fetchUserInfoRes = client
					.DigitalHealthFetchUserInfo(_strBaseURL + "procFetchUserInfo", fetchUserInfoReq);
			return fetchUserInfoRes;
			/*if(fetchUserInfoRes == null)
			{
				//锟斤拷取锟斤拷息失锟斤拷
				System.out.println("FetchUserInfo Failed!");
			}
			else
			{
				System.out.println("");
				System.out.println("[DigitalHealthFetchUserInfo]");
				System.out.println("Transaction_Id: " + fetchUserInfoRes.getTransactionId());
				System.out.println("Login_Name: " + fetchUserInfoRes.getLoginName());
				System.out.println("User_Number: " + fetchUserInfoRes.getUserNumber());
				System.out.println("Fetch_Status: " + fetchUserInfoRes.getFetchStatus());
				System.out.println("User_Gender: " + fetchUserInfoRes.getUserGender());
				System.out.println("User_Height: " + fetchUserInfoRes.getUserHeight());
				System.out.println("User_Weight: " + fetchUserInfoRes.getUserWeight());
				System.out.println("Step_Length: " + fetchUserInfoRes.getStepLength());
				System.out.println("Run_Step_Length: " + fetchUserInfoRes.getRunStepLength());
				System.out.println("Day_Plan_Step_Count: " + fetchUserInfoRes.getDayPlanStepCount());
				
				if(fetchUserInfoRes.getFetchStatus() == 0)
				{
					//锟斤拷取锟斤拷息锟缴癸拷
				}
				else
				{
					//锟斤拷取锟斤拷息失锟斤拷
					System.out.println("FetchUserInfo Failed!");
				}//else
			}//else
			*/} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 获取用户每日步数
	 */
	public static LineChartInfo getDailyStep(String username) {

		// 临时使用 test@163.com 用户
		if (StringUtils.isEmpty(username)) {
			username = "lee";
		}
		String url = _strBaseURL + "getsns?username=" + username;
		String resultAll = HttpUtils.sendHttpRequest(url);

		// 要显示的所用数据
		LineChartInfo lineChart = new LineChartInfo();
		lineChart = getLineChart(resultAll, Utils.CYCLESTEP);

		// 要显示的init数据
		LineChartInfo initLineChart = new LineChartInfo();
		initLineChart = getLineChart(resultAll, Utils.INITSTEP);

		lineChart.setMinX(NumberUtils.min(initLineChart.getX()));
		lineChart.setMaxX(NumberUtils.max(initLineChart.getX()));
		lineChart.setMinY(NumberUtils.min(initLineChart.getY()));
		lineChart.setMaxY(NumberUtils.max(initLineChart.getY()));
		return lineChart;

	}

	/**
	 * 获取x,y数据
	 * 
	 * @param resultAll
	 *            server数据
	 * @param n
	 *            显示数据日期天数
	 * @return
	 */
	private static LineChartInfo getLineChart(String resultAll, int n) {
		String[] userInfo = null;
		DailyStep dailyStep = null;

		List<String> showDate = null;
		// 需要显示的所用日期（目前是30天）
		showDate = Utils.getDayListInStr(n, Utils.getNowDate());

		String[] result = resultAll.split(";");
		HashMap<String, Double> resultMap = new HashMap<String, Double>();
		for (int i = 0; i < result.length; i++) {
			resultMap.put(result[i].split(":")[0], Double.valueOf(result[i].split(":")[1]) / 1000);
		}

		int j = 0;
		double[] showStep = new double[n];
		// 获取最近n天数据
		for (int i = 0; i < n; i++) {

			// 需要显示的日期有步数数据
			if (resultMap.containsKey(showDate.get(i))) {
				showStep[i] = resultMap.get(showDate.get(i));
				j++;
			} else {
				showStep[i] = 0;
			}

		}

		// 类型转换

		LineChartInfo lineChart = new LineChartInfo();

		lineChart.setX(Utils.list2LongArray(showDate));
		lineChart.setY(showStep);

		return lineChart;
	}

}
